package org.daochong.lang.database;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.daochong.lang.JdbcTemplate;
import org.daochong.lang.Page;
import org.daochong.lang.PageResult;

public class Oracle extends BaseDatabase {

	public Oracle() {
		this.varchar = "VARCHAR2";
	}

	public PageResult<Map<String, Object>> listObjects(JdbcTemplate jdbc, Page page, String sql, Object... params)
			throws SQLException {
		PageResult<Map<String, Object>> result = new PageResult<Map<String, Object>>();
		result.setPage(page.getPage());
		result.setPageSize(page.getPageSize());
		if (result.getPage() <= 0) {
			result.setPage(1);
		}
		if (result.getPageSize() <= 0) {
			result.setPageSize(20);
		}
		int count = jdbc.firstIntValue("select count(*) from (" + sql + ") daochong_temp", params);
		result.setCount(count);
		String ns = "select * from (select daochong_temp.*,rownum daochong_count from (" + sql
				+ ") daochong_temp) daochong_list where daochong_count>" + (result.getPage() - 1) * result.getPageSize()
				+ " and daochong_count<=" + (result.getPage() * result.getPageSize());
		List<Map<String, Object>> ls = jdbc.listObjects(ns, params);
		if (ls != null) {
			for (Map<String, Object> map : ls) {
				map.remove("DAOCHONG_COUNT");
			}
		}
		result.setData(ls);
		return result;
	}

	public List<String> getTableList(JdbcTemplate jdbc) throws SQLException {
		List<String> ts = new ArrayList<String>();
		Connection cn = null;
		try {
			cn = jdbc.getDataSource().getConnection();
			String sql = "select tname from tab where tabtype='TABLE'";
			Statement st = cn.createStatement();
			ResultSet rs = st.executeQuery(sql);
			while (rs.next()) {
				ts.add(rs.getString(1).toUpperCase());
			}
			rs.close();
			st.close();
			return ts;
		} catch (SQLException e) {
			throw e;
		} finally {
			if (cn != null) {
				try {
					cn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

	}

}
